#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h> 
#include "sqlite3.h"
#include "global.h"
#define FILEPATH_MAX (80)

int a9_sqlite3_match(void)
{
	struct sqlite3 * pdb;
	int result;
	char * errmsg = NULL;
	char **dbResult = NULL; 
	int nRow = -1, nColumn = -1;
	//char dbName[] = "data.db";
	//char *pPath = NULL;
	char sqlSelect[SIZE] = {0};
	/*
    pPath = (char *) malloc (FILEPATH_MAX + 10);
    if (NULL == pPath)
    {
        return -1;
    }
    memset(pPath, 0, FILEPATH_MAX + 10);
    if (NULL == getcwd(pPath, FILEPATH_MAX))
	{
		return -1;
	}
    printf("%s %d\n",pPath,strlen(pPath));
    memcpy(pPath + strlen(pPath), dbName, strlen(dbName));
    printf("%s %d\n",pPath,strlen(pPath));
    //db name end
	*/
    //open or create db
    result = sqlite3_open("/root/data.db",&pdb);
    if(SQLITE_OK != result || NULL == pdb)
    {
      printf("invoke sqlite3_open function error!\n");
	  //free(pPath);
	  //pPath = NULL;
      return -1;
    }
	
	
	
	if(('1' == m_aUsbKey[0])&&(6 == strlen(m_aUsbKey)))
	{
		printf("get password %s \r\n",m_aUsbKey);
        sprintf(sqlSelect,"select name from user where password = '%s'",m_aUsbKey);
		result = sqlite3_get_table( pdb, sqlSelect , &dbResult, &nRow, &nColumn, &errmsg );
		if(0 < nRow)
		{
            strcpy(m_aRelMat,c_aHoms);
		}
		if(0 == nRow)
        {
            strcpy(m_aRelMat,c_aHomf);
        }
	}
	else if(('2' == m_aUsbKey[0])&&(4 == strlen(m_aUsbKey)))
	{
		printf("get doornum %s \r\n",m_aUsbKey);
        sprintf(sqlSelect,"select IP from user where homenum = '%s'",m_aUsbKey);
		result = sqlite3_get_table( pdb, sqlSelect, &dbResult, &nRow, &nColumn, &errmsg );
		if(0 < nRow)
		{
            strcpy(m_aRelMat,c_aFris);
            strcpy(m_aIpAd,dbResult[1]);
		printf("db IP = %s\r\n",m_aIpAd);
		}
		if(0 == nRow)
		{
            strcpy(m_aRelMat,c_aFrif);
		}
	}
    else
    {
        printf("input key error!\n");
        result = sqlite3_close(pdb);
        pdb = NULL;
        return 0;
    }
    sqlite3_free_table(dbResult);
    result = sqlite3_close(pdb);
    pdb = NULL;
    return 0;
}
